package com.liuxu.topnews.utils;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import com.liuxu.topnews.service.AccessService;
import com.liuxu.topnews.bean.Point;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import static android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK;
import static android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME;

public class AccessibilityUtils {
    public static int search_count=3;
    private static final String TAG = "lch";
    private static AccessibilityUtils mInstance = null;
    private static StringBuilder sb;
    private static int tabcount = -1;
    int TYPE_TEXT = 1;
    int TYPE_VIEW_NAME = 2;

    public AccessibilityUtils() {
    }

    private static void analysisPacketInfo(AccessibilityNodeInfo var0, int... var1) {
        if (var0 != null) {
            StringBuilder var5 = new StringBuilder();
            int var2;
            if (tabcount > 0) {
                for(var2 = 0; var2 < tabcount; ++var2) {
                    var5.append("  ");
                }
            }

            if (var1 != null && var1.length > 0) {
                StringBuilder var6 = new StringBuilder();

                for(var2 = 0; var2 < var1.length; ++var2) {
                    var6.append(var1[var2]).append(".");
                }

                var5.append(var6).append(" ");
            }

            String[] var8 = var0.getClassName().toString().split("\\.");
            String var9 = var8[var8.length - 1];
            Rect var7 = new Rect();
            var0.getBoundsInScreen(var7);
            var5.append(var9).append("  rect:").append(var7.toString()).append("  text:").append(var0.getText()).append("   Description:").append(var0.getContentDescription());
            var5.append("\n");
            LogUtil.getInstance().show("allnode", var5.toString());
            int var3 = var0.getChildCount();
            if (var3 > 0) {
                ++tabcount;
                int var4 = var1.length + 1;
                var1 = Arrays.copyOf(var1, var4);

                for(var2 = 0; var2 < var3; ++var2) {
                    var1[var4 - 1] = var2;
                    analysisPacketInfo(var0.getChild(var2), var1);
                }

                --tabcount;
                return;
            }
        }

    }

    public static AccessibilityUtils getInstance() {
        if (mInstance == null) {
            mInstance = new AccessibilityUtils();
        }

        return mInstance;
    }

    public static void goBack(AccessibilityService var0) {
        if (var0 != null) {
            var0.performGlobalAction(1);
        }
    }

    public static void onClick(AccessibilityNodeInfo var0) {
        if (var0 != null) {
            if (!var0.isClickable()) {
                LogUtil.getInstance().show("lch", "不可以点击----------" + var0.toString());
                onClick(var0.getParent());
                return;
            }

            LogUtil.getInstance().show("lch", "可以点击----------" + var0.toString());
            var0.performAction(16);
        }

    }

    private void recycle(AccessibilityNodeInfo Node, List<AccessibilityNodeInfo> NodeInfos) {
        if (Node != null) {
            NodeInfos.add(Node);
            int var4 = Node.getChildCount();

            for(int var3 = 0; var3 < var4; ++var3) {
                AccessibilityNodeInfo var5 = Node.getChild(var3);
                if (var5 != null) {
                    this.recycle(var5, NodeInfos);
                }
            }
        }

    }

    public static void scrollDown(AccessibilityNodeInfo var0) {
        if (var0 != null) {
            var0.performAction(4096);
        }
    }

    public static void scrollUp(AccessibilityNodeInfo var0) {
        if (var0 != null) {
            var0.performAction(8192);
        }
    }

    public static void showAllInfo(AccessibilityNodeInfo var0) {
        tabcount = 0;
        analysisPacketInfo(var0);
    }

    public AccessibilityNodeInfo findText(AccessibilityService var1, String var2) {
        return this.findText(var1, var2, 0);
    }

    public AccessibilityNodeInfo findText(AccessibilityService var1, String var2, int var3) {
        AccessibilityNodeInfo var5 = var1.getRootInActiveWindow();
        if (var5 != null) {
            AccessibilityNodeInfo var4 = this.findText2TextView(var5, var2, var3);
            if (var4 != null) {
                return var4;
            }

            LogUtil.getInstance().show("lch", "findText方法 nodeInfoTextView is null - " + var2);
            var5 = this.getViewByType(var5, var2, var3, this.TYPE_TEXT);
            if (var5 != null) {
                return var5;
            }

            LogUtil.getInstance().show("lch", "findText方法 nodeInfoView is null - " + var2);
        } else {
            LogUtil.getInstance().show("lch", "findText方法 AccessService.getInstance().getRootInActiveWindow is null:" + var2);
        }

        return null;
    }

    public AccessibilityNodeInfo findText2TextView(AccessibilityNodeInfo var1, String var2, int var3) {
        List var4 = var1.findAccessibilityNodeInfosByText(var2);
        return var4 != null && var3 < var4.size() ? (AccessibilityNodeInfo)var4.get(var3) : null;
    }

    public AccessibilityNodeInfo findText2View(AccessibilityNodeInfo var1, String var2) {
        return this.findText2View(var1, (String)var2, 0);
    }

    public AccessibilityNodeInfo findText2View(AccessibilityNodeInfo var1, String var2, int var3) {
        ArrayList var4 = new ArrayList();
        List var9 = this.getAllNodeInfoList(var1);
        if (var9 != null && !var9.isEmpty()) {
            Iterator var5 = var9.iterator();

            label37:
            while(true) {
                AccessibilityNodeInfo var6;
                CharSequence var7;
                CharSequence var8;
                do {
                    do {
                        if (!var5.hasNext()) {
                            break label37;
                        }

                        var6 = (AccessibilityNodeInfo)var5.next();
                    } while(var6 == null);

                    var7 = var6.getText();
                    var8 = var6.getContentDescription();
                } while((var7 == null || !var2.equals(var7.toString())) && (var8 == null || !var2.equals(var8.toString())));

                var4.add(var6);
            }
        }

        if (!var4.isEmpty() && var3 < var4.size()) {
            var9.clear();
            return (AccessibilityNodeInfo)var4.get(var3);
        } else {
            var9.clear();
            return null;
        }
    }

    public AccessibilityNodeInfo findText2View(AccessibilityNodeInfo var1, String[] var2) {
        return this.findText2View(var1, (String[])var2, 0);
    }

    public AccessibilityNodeInfo findText2View(AccessibilityNodeInfo var1, String[] var2, int var3) {
        ArrayList var6 = new ArrayList();
        List var12 = this.getAllNodeInfoList(var1);
        if (var12 != null && !var12.isEmpty()) {
            Iterator var7 = var12.iterator();

            label46:
            while(true) {
                AccessibilityNodeInfo var8;
                do {
                    if (!var7.hasNext()) {
                        break label46;
                    }

                    var8 = (AccessibilityNodeInfo)var7.next();
                } while(var8 == null);

                int var5 = var2.length;

                for(int var4 = 0; var4 < var5; ++var4) {
                    String var9 = var2[var4];
                    CharSequence var10 = var8.getText();
                    CharSequence var11 = var8.getContentDescription();
                    if (var10 != null && var9.equals(var10.toString()) || var11 != null && var9.equals(var11.toString())) {
                        var6.add(var8);
                    }
                }
            }
        }

        if (!var6.isEmpty() && var3 < var6.size()) {
            var12.clear();
            return (AccessibilityNodeInfo)var6.get(var3);
        } else {
            var12.clear();
            return null;
        }
    }

    public void findText2ViewAndClick(AccessibilityNodeInfo var1, String var2) {
        onClick(this.findText2View(var1, var2));
    }

    public void findTextAndClick(AccessibilityService var1, String var2) {
        this.findTextAndClick(var1, var2, 0);
    }

    public void findTextAndClick(AccessibilityService var1, String var2, int var3) {
        AccessibilityNodeInfo var4 = this.findText(var1, var2, var3);
        if (var4 != null) {
            LogUtil.getInstance().show("lch", "点击文案 - " + var2);
            onClick(var4);
        } else {
            LogUtil.getInstance().show("lch", "findTextAndClick clickInfo is null - " + var2);
        }
    }

    public AccessibilityNodeInfo findViewName(AccessibilityService var1, String var2) {
        return this.findViewName((AccessibilityService)var1, var2, 0);
    }

    public AccessibilityNodeInfo findViewName(AccessibilityService var1, String var2, int var3) {
        AccessibilityNodeInfo var4 = var1.getRootInActiveWindow();
        if (var4 != null) {
            return this.findViewName(var4, var2, var3);
        } else {
            LogUtil.getInstance().show("lch", "findViewName方法 AccessService.getInstance().getRootInActiveWindow is null:16843087");
            return null;
        }
    }

    public AccessibilityNodeInfo findViewName(AccessibilityNodeInfo var1, String var2) {
        return this.getViewByType(var1, var2, 0, this.TYPE_VIEW_NAME);
    }

    public AccessibilityNodeInfo findViewName(AccessibilityNodeInfo var1, String var2, int var3) {
        return this.getViewByType(var1, var2, var3, this.TYPE_VIEW_NAME);
    }

    public void findViewNameClick(AccessibilityNodeInfo var1, String var2) {
        var1 = this.getViewByType(var1, var2, 0, this.TYPE_VIEW_NAME);
        if (var1 != null) {
            onClick(var1);
        }

    }

    public List<AccessibilityNodeInfo> getAllNodeInfoList(AccessibilityNodeInfo Node) {
        ArrayList NodeInfos = new ArrayList();
        if (Node != null) {
            this.recycle(Node, NodeInfos);
            return NodeInfos;
        } else {
            LogUtil.getInstance().show("lch", "getAllNodeInfoList方法 info is null");
            return NodeInfos;
        }
    }

    public Point getPointByText(AccessibilityNodeInfo var1, String var2) {
        return this.getPointByText(var1, new String[]{var2});
    }

    public Point getPointByText(AccessibilityNodeInfo var1, String[] var2) {
        var1 = this.findText2View(var1, var2);
        if (var1 != null) {
            Rect var4 = new Rect();
            var1.getBoundsInScreen(var4);
            int var3 = AndroidUtils.getStatusBarHeight();
            if (var4.bottom > 0 && var4.bottom < AndroidUtils.getDisplayHeight() - var3 && var4.left > 0 && var4.right < AndroidUtils.getDisplayWidth()) {
                return new Point(var4.left + (var4.right - var4.left) / 2, var4.top + (var4.bottom - var4.top) / 2);
            }
        }

        return null;
    }

    public AccessibilityNodeInfo getViewByType(AccessibilityNodeInfo Node, String var2, int var3, int var4) {
        ArrayList var6 = new ArrayList();
        List var7 = this.getAllNodeInfoList(Node);
        if (var7 != null && !var7.isEmpty()) {
            Iterator var8 = var7.iterator();

            while(var8.hasNext()) {
                AccessibilityNodeInfo var9 = (AccessibilityNodeInfo)var8.next();
                if (var9 != null) {
                    String var5 = "";
                    Object var11;
                    if (var4 == this.TYPE_TEXT) {
                        var11 = var9.getText();
                    } else {
                        var11 = var5;
                        if (var4 == this.TYPE_VIEW_NAME) {
                            CharSequence var10 = var9.getClassName();
                            var11 = var5;
                            if (var10 != null) {
                                String[] var12 = var10.toString().split("\\.");
                                var11 = var12[var12.length - 1];
                            }
                        }
                    }

                    if (var11 != null && var2.equals(((CharSequence)var11).toString())) {
                        var6.add(var9);
                    }
                }
            }
        }

        if (!var6.isEmpty() && var3 < var6.size()) {
            var7.clear();
            return (AccessibilityNodeInfo)var6.get(var3);
        } else {
            var7.clear();
            return null;
        }
    }

    public static List<AccessibilityNodeInfo> findNodesByText(String text) throws InterruptedException {
        List<AccessibilityNodeInfo> result = new ArrayList<>();
        int time=search_count;
        Log.v("按照文字查找",text);
        while (result.size() == 0&&time>0){
            AccessibilityNodeInfo nodeInfo = AccessService.getInstance().getRootInActiveWindow();
            if (nodeInfo != null) {
                Log.v("有控件，找",text);
                result=nodeInfo.findAccessibilityNodeInfosByText(text);
            }
            Thread.sleep(1000);
            time-=1;
        }
        return result;
    }
    public static List<AccessibilityNodeInfo> findNodesById(String viewId) throws InterruptedException {
        List<AccessibilityNodeInfo> result = new ArrayList<>();
        int time=search_count;
        Log.v("按照控件查找",viewId);
        while (result.size() == 0&&time>0){
            AccessibilityNodeInfo nodeInfo = AccessService.getInstance().getRootInActiveWindow();
            if (nodeInfo != null) {
                Log.v("有控件，找",viewId);
                result=nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
            }
            Thread.sleep(1000);
            time-=1;
        }
        return result;
    }
    public void set_text(List<AccessibilityNodeInfo> Node,String word) throws Exception {
        if (Node.size() != 0) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, word);
            Node.get(0).performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        }
        else {
            throw new Exception("找不到");
        }
    }



    /**
     * 模拟点击事件
     *
     * @param nodeInfo nodeInfo
     */
    public boolean performViewClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return false;
        }
        while (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                return true;
            }
            nodeInfo = nodeInfo.getParent();
        }
        return false;
    }

    /**
     * 模拟主页操作
     */
    public void performHomeClick() throws InterruptedException {
        Thread.sleep(1000);
        Log.v("全局操作","返回");
        AccessService.getInstance().performGlobalAction(GLOBAL_ACTION_HOME);
    }
    /**
     * 模拟返回操作
     */
    public void performBackClick() throws InterruptedException {
        Thread.sleep(1000);
        Log.v("全局操作","返回");
        AccessService.getInstance().performGlobalAction(GLOBAL_ACTION_BACK);
    }

    /**
     * 模拟下滑操作
     */
    public void performScrollBackward(int time) {
        while (time>0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","下滑");
            AccessService.getInstance().performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
            time-=1;
        }
    }

    /**
     * 模拟上滑操作
     */
    public void performScrollForward(int time) {
        while (time>0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v("全局操作","上滑");
            AccessService.getInstance().performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
            time-=1;
        }
    }

    /**
     * 查找对应文本的View
     *
     * @param text text
     * @return View
     */
    public AccessibilityNodeInfo findViewByText(String text) {
        return findViewByText(text, false);
    }

    /**
     * 查找对应文本的View
     *
     * @param text      text
     * @param clickable 该View是否可以点击
     * @return View
     */
    public AccessibilityNodeInfo findViewByText(String text, boolean clickable) {
        AccessibilityNodeInfo accessibilityNodeInfo = AccessService.getInstance().getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null && (nodeInfo.isClickable() == clickable)) {
                    return nodeInfo;
                }
            }
        }
        return null;
    }

    /**
     * 查找对应ID的View
     *
     * @param id id
     * @return View
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public AccessibilityNodeInfo findViewByID(String id) {
        AccessibilityNodeInfo accessibilityNodeInfo = AccessService.getInstance().getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return null;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    return nodeInfo;
                }
            }
        }
        return null;
    }

    public boolean clickTextViewByText(String text) throws InterruptedException {
        Log.v("按照文字查找",text);
            Thread.sleep(1000);
        AccessibilityNodeInfo accessibilityNodeInfo = AccessService.getInstance().getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return false;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    Log.v("点击：",text);
                    if (performViewClick(nodeInfo)){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public boolean ClickTextViewById(String id) throws InterruptedException {
        Log.v("按照ID查找",id);
            Thread.sleep(1000);
        AccessibilityNodeInfo accessibilityNodeInfo = AccessService.getInstance().getRootInActiveWindow();
        if (accessibilityNodeInfo == null) {
            return false;
        }
        List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
        if (nodeInfoList != null && !nodeInfoList.isEmpty()) {
            for (AccessibilityNodeInfo nodeInfo : nodeInfoList) {
                if (nodeInfo != null) {
                    Log.v("点击：",id);
                    if (performViewClick(nodeInfo)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
    public AccessibilityNodeInfo  findTextViewByDesc(String desc) throws InterruptedException {
        Log.v("按照Desc查找",desc);
        Thread.sleep(1000);
        AccessibilityNodeInfo Nodes = AccessService.getInstance().getRootInActiveWindow();
        if (Nodes == null) {
            return null;
        }else {
            return findDesc(Nodes,desc);
        }
    }
    public AccessibilityNodeInfo findDesc(AccessibilityNodeInfo Nodes,String desc)  {
        Log.v("查找增加","一层");
        for (int i=0;i<Nodes.getChildCount();i++){
            AccessibilityNodeInfo Node=Nodes.getChild(i);
            if (Node==null){
                Log.v("此对象","为空");
            }else {
                if(Node.getContentDescription()==null||!Node.getContentDescription().toString().equals(desc)){
                    if (Node.getChildCount()>0) {
                        findDesc(Node, desc);
                    }
                }else {
                    Log.v("找到目标",Node.getContentDescription().toString());
                    return Node;
                }
            }
        }
        return null;
    }

    /**
     * 模拟输入
     *
     * @param nodeInfo nodeInfo
     * @param text     text
     */
    public void inputText(AccessibilityNodeInfo nodeInfo, String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bundle arguments = new Bundle();
            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ClipboardManager clipboard = (ClipboardManager) AccessService.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", text);
            clipboard.setPrimaryClip(clip);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }
    public void readslowbyas(int uptime,int downtime) throws InterruptedException {
        performScrollForward(uptime);
        performScrollBackward(downtime);
        performBackClick();
    }
}
